<?php
// +----------------------------------------------------------------------
// | INPHP
// | Copyright (c) 2023 https://inphp.cc All rights reserved.
// | Author: 幺月儿(https://gitee.com/lulanyin) Email: inphp@qq.com
// | 该文件的开源协议以所在项目的LICENSE文件为准，请遵守开源协议要求
// +----------------------------------------------------------------------
// | 常用方法
// +----------------------------------------------------------------------
/**
 * 过滤非法字符
 * @param null|string $string
 * @return string
 */
function filterIllegalString(?string $string): string {
    if (empty($string)) {
        return "";
    }
    $config = \Inphp\Core\Modules::getModule("cms")->getConfig();
    $config = is_array($config) ? $config : [];
    $illegalString = $config["illegalString"] ?? "";
    $illegalString = !empty($illegalString) ? explode(",", $illegalString) : [];
    foreach ($illegalString as $is) {
        $string = str_replace($is, "*", $string);
    }
    return $string;
}

if (!function_exists('decodeNickname')) {
    /**
     * 昵称解码
     * @param string|null $nickname
     * @return string
     */
    function decodeNickname(?string $nickname = null): string
    {
        if (empty($nickname)) {
            return "";
        }
        if (stripos($nickname, "data:text/plant;base64,") === 0) {
            $nickname = base64_decode(substr($nickname, 23));
        }
        return $nickname;
    }
}

/**
 * 响应前，做模板输出
 */
\Inphp\Core\Middlewares::push("beforeEnd", function (...$args) {
    $module = \Inphp\Core\Modules::getModule();
    if ($module->id === "cms") {
        $response = $args[0] ?? getHttpResponse();
        if ($response instanceof \Inphp\Core\Services\Http\Response) {
            $controller = $response->getRouterStatus()->controller[0] ?? null;
            if ($controller instanceof \app\cms\http\web\controller) {
                //统一响应
                $controller->beforeEnd();
            }
        }
    }
});

/**
 * 清除缓存
 * @param int $siteId
 * @param string $groupName
 */
function CMS_cleanCache(int $siteId, string $groupName = 'all') {
    @exec("php ".ROOT."/bin/cmd app.cms.cmd.cleanCache siteId={$siteId} groupName={$groupName} > /dev/null 2>&1 &");
}

/**
 * 生成地址
 * @param array $data
 * @param string $type
 * @return string
 */
function makeCMSUrl(array $data, string $type = "archive"): string {
    if ($type == "archive" || $type == "category") {
        return !empty($data["url"]) ? $data["url"] : ("/cms/{$type}/".(!empty($data['index']) ? $data["index"] : $data["id"]).".html");
    }
    return "";
}

/**
 * 匹配站点
 * @return array
 */
function matchCMSSite(): array {
    $sites = \app\cms\model\SiteModel::getCache();
    if (empty($sites)) {
        return [];
    }
    $client = getClient();
    $site = [];
    if (isset($sites[$client->origin])) {
        //存在与来源域名一致的站点
        $site =  $sites[$client->origin];
    } elseif (isset($sites[$client->host])) {
        //存在与请求域名一致的站点
        $site =  $sites[$client->host];
    } else {
        //取默认站点
        $dfSite = [];
        foreach ($sites as $site) {
            if ($site["default"] == 1) {
                $dfSite = $site;
            }
        }
        $site = !empty($dfSite) ? $dfSite : reset($sites);
    }
    return !empty($site) && $site["state"] == 1 ? $site : [];
}

/**
 * 随机图片
 * @param string $text 可在图片上增加字符
 * @return string
 */
function CMS_randImage(string $text = ''): string
{
    $rand = rand(1, 20);
    $lastRand = \Inphp\Core\Context::get("CMS_RAND_IMAGE") ?? 0;
    if ($lastRand == $rand) {
        //防连续图片重复，影响美观
        return CMS_randImage($text);
    }
    \Inphp\Core\Context::set("CMS_RAND_IMAGE", $rand);
    return assetsUrl("/template/default/assets/images/tmp/" . ($rand < 10 ? "0{$rand}" : $rand).".jpg", "cms");
}